<template>
	<div ref="chartRef" :style="{height, width}"></div>
</template>
<script lang="ts">
	import {defineComponent, onMounted, PropType, ref, Ref, reactive, watchEffect} from 'vue';
	import {useECharts} from '/@/hooks/web/useECharts';
	import {cloneDeep} from 'lodash-es';
	export default defineComponent({
		name: 'bar',
		props: {
			chartData: {
				type: Array,
				default: () => [],
			},
			option: {
				type: Object,
				default: () => ({}),
			},
			width: {
				type: String as PropType<string>,
				default: '100%',
			},
			height: {
				type: String as PropType<string>,
				default: '160px',
			},
			seriesColor: {
				type: String,
				default: '#1890ff',
			},
		},
		setup(props) {
			const chartRef = ref<HTMLDivElement | null>(null);
			const {setOptions, resize} = useECharts(chartRef as Ref<HTMLDivElement>);
			onMounted(() => {
				window.addEventListener('resize', function () {
					resize();
				});
			});
			let current = props.chartData.count; // 当前用量

			let seriesColor = props.seriesColor;
			let all = 100; // 总量
			const option = reactive({
				title: {
					text: props.chartData.name,
					subtext: props.chartData.unit,
					left: 1 * 30 + 20 + '%',
					top: '50%',
					textAlign: 'center',

					textStyle: {
						fontWeight: 'normal',
						fontSize: '12',
						color: '#7D8590',
						textAlign: 'center',
						width: '100px',
						background: '#fff',
					},
				},
				series: [
					{
						type: 'pie',
						label: {
							show: false,
						},
						center: ['50%', '40%'],
						radius: ['70%', '85%'],
						hoverAnimation: false,
						startAngle: 180,
						data: [
							{
								name: '用量',
								value: current,
								itemStyle: {
									color: seriesColor,
								},
								label: {
									normal: {
										formatter: function (params) {
											return params.value;
										},
										position: 'center',
										show: true,
										textStyle: {
											fontSize: '20',
											color: seriesColor,
										},
									},
								},
							},
							{
								name: 'rest', // 实际显示部分是总量-用量
								value: all - current,
								itemStyle: {
									color: '#1a2a47',
								},
							},
							{
								name: 'bottom',
								value: all,
								itemStyle: {
									color: 'transparent',
								},
							},
						],
					},
				],
			});

			watchEffect(() => {
				props.chartData && initCharts();
			});

			function initCharts() {
				if (props.option) {
					Object.assign(option, cloneDeep(props.option));
				}

				setOptions(option);
			}
			return {chartRef};
		},
	});
</script>
